import React, { Component } from 'react';
import { connect } from 'react-redux';
import { deepCopy, messages } from 'share/common';
import { Affix, Button, Form, message, Switch, Input } from 'antd';
import Chooser from 'components/chooser';
import menuRoute from 'routes/menuRoute';
import errorMessage from "share/errorMessage";
import { LanguageInput } from 'components/index';
import reimburseService from '../reimbursement/reimbursement.service';
import ReimbursementSubmissionRadio from './reimbursement-submission-radio';
import 'styles/expense-reimbursement-control/reimbursement/reimbursement-submission.scss';
import { ruleItems } from 'containers/expense-reimbursement-control/expense-standard/reimbursement-submission/data-sources';

const FormItem = Form.Item;

class ReimbursementSubmissionNew extends Component {

  component = {
    Input,
    Switch,
    Chooser,
    LanguageInput,
    ReimbursementSubmissionRadio
  };

  constructor(props) {
    super(props);
    this.state = {
      i18n: {}
    };
  }

  componentWillMount() {
    this.handleFormItems();
  }

  componentDidMount() {
    const { form: { setFieldsValue }, params: { info } } = this.props;
    if (!info) {
      setFieldsValue({ controlLevel: 'WARN', status: true });
    }
  }

  handleFormItems = () => {
    const { tenantMode, params: { setOfBooksId, info }, company: { companyOID, name } } = this.props;
    let formItems = deepCopy(ruleItems);
    formItems.map(item => {
      if (info) {
        item.initialValue = info[item.id];
      }
      if (item.id === 'name') {
        item.length = 100;
        item.required = true;
        item.params = {
          placeholder: messages('common.please.input'/*请输入*/),
          nameChange: (value, i18nName) => this.handleI18nChange(value, i18nName, 'name'),
          inpRule: [{
            length: 100,
            language: 'zh_cn'
          }, {
            length: 100,
            language: 'en'
          }]
        };
        return item;
      }

      if (item.id === 'forms') {
        item.required = false;
        item.params = {
          placeholder: messages('expense-reimbursement-control.key28')/*通用*/,
          type: 'select_form',
          valueKey: 'formOID',
          labelKey: 'formName',
          listExtraParams: {}
        };
        item.params.listExtraParams.formTypeList = [3001, 3002, 3003];
        tenantMode && (item.params.listExtraParams.setOfBooksId = setOfBooksId);
        !tenantMode && (item.params.listExtraParams.companyOID = companyOID);
        return item;
      }

      if (item.id === 'companys') {
        item.required = false;
        item.params = {
          placeholder: messages('expense-reimbursement-control.key28')/*通用*/,
          type: 'available_company_setOfBooks',
          valueKey: 'companyOID',
          labelKey: 'name',
          listExtraParams: { enabled: true, setOfBooksId },
        };
        if (!tenantMode) { //公司模式下
          item.params.disabled = true;
          item.initialValue = [{ name, companyOID }];
        }
        return item;
      }

      if (item.id === 'controlLevel') {
        item.required = true;
        item.params = {
          onChange: this.handleControlLevel,
          options: [{
            value: 'WARN',
            title: messages('expense-reimbursement-control.key46')/*警告*/
          }, {
            value: 'FORBID',
            title: messages('expense-reimbursement-control.key47')/*禁止*/
          }]
        };
        return item;
      }

      if (item.id === 'status') {
        item.valuePropName = 'checked';
        return item;
      }

      if (item.id === 'message') {
        item.required = true;
        item.params = {
          inpRule: [{
            length: 300,
            language: 'zh_cn'
          }, {
            length: 300,
            language: 'en'
          }],
          textArea: true,
          placeholder: messages('common.max.characters.length', { max: 300 }/*最多输入300个字符*/),
          nameChange: (value, i18nName) => this.handleI18nChange(value, i18nName, 'message')
        };
      }
      return item;
    });
    if (info) {
      const { message, name, i18n } = info;
      formItems.splice(0, 0, {
        id: 'code',
        type: 'Input',
        label: messages('expense-reimbursement-control.key18')/*规则编码*/,
        params: {
          disabled: true
        },
        required: true,
        initialValue: info.code
      });
      this.setState({ message, name, i18n, formItems });
    } else {
      this.setState({ formItems });
    }
  };
  handleControlLevel = (controlLevel) => {
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue({ controlLevel });
  };

  handleI18nChange = (value, i18nName, id) => {
    let { i18n } = this.state;
    i18n[id] = i18nName;
    this.setState({ [id]: value, i18nName });
  };

  handleCancel = () => {
    let listUrl = menuRoute.getRouteItem('expense-standard').url;
    this.context.router.push(listUrl);
  };

  handleSave = (e) => {
    e.preventDefault();
    const { i18n } = this.state;
    const { params: { setOfBooksId, info } } = this.props;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.i18n = i18n;
        values.businessType = 1002;
        const service = () => {
          reimburseService.newOrEditRule({ ...info, ...values }, setOfBooksId)
            .then(res => {
              if (info) {
                this.props.close('rule');
              } else {
                let ruleDetailUrl = menuRoute.getRouteItem('reimbursement-submission-detail').url;
                this.context.router.replace(ruleDetailUrl.replace(':setOfBooksId', setOfBooksId).replace(':ruleOID', res.data));
                message.success(messages('common.save.success', { name: '' })/*保存成功*/);
              }
            })
            .catch(e => {
              errorMessage(e.response);
            })
            .finally(() => {
              this.setState({ submitLoading: false });
            });
        };
        this.setState({ submitLoading: true }, service);

      }
    });
  };

  renderFormItem = (item) => {
    const { params: { info } } = this.props;
    if (item.type === 'LanguageInput') {
      item.params.name = this.state[item.id];
      item.params.i18nName = this.state.i18n[item.id];
      item.params.isEdit = !!info;
    }
    return React.createElement(this.component[item.type], item.params);
  };


  render() {
    const { formItems, submitLoading } = this.state;
    const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 10 } };
    const { form: { getFieldDecorator }, params: { info } } = this.props;
    return (
      <section className="reimbursement-submission">
        <Form onSubmit={this.handleSave}>
          {formItems.map(item => {
            let rules = [{ required: item.required, message: messages('common.please.enter') }];
            if (item.rules) rules.push(item.rules);
            return (
              <FormItem label={item.label}  {...formItemLayout}>
                {
                  getFieldDecorator(item.id,
                    {
                      rules: rules,
                      valuePropName: item.valuePropName || 'value',
                      initialValue: item.initialValue
                    }
                  )(this.renderFormItem(item))
                }
              </FormItem>
            );
          })}
          <Affix offsetBottom={0} className={`reimbursement-submission-footer ${info ? 'reimbursement-submission-left' : ''}`}>
            <Button type="primary" htmlType="submit" loading={submitLoading}>
              {info && info.ruleOID ? messages('common.save'/*保存*/) : messages('expense-reimbursement-control.key26')/*创建*/}
            </Button>
            <Button onClick={this.handleCancel} className="reimbursement-submission-cancel">
              {messages('common.cancel')/*取消*/}
            </Button>
          </Affix>
        </Form>
      </section>
    );
  }

}


function mapStateToProps(state) {
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode,
    languageList: state.login.languageList,
    language: state.main.language
  };
}

ReimbursementSubmissionNew.contextTypes = {
  router: React.PropTypes.object
};

const WrappedComponent = Form.create()(ReimbursementSubmissionNew);

export default connect(mapStateToProps)(WrappedComponent);
